#include "RTSP.h"
#include "fvideodecode.h"
#include "faudiodecode.h"

#include <QDebug>
#include <SDL2/SDL.h>
extern "C" {
#include <libavformat/avformat.h>
#include <libswresample/swresample.h>
#include <libswscale/swscale.h>
#include <libavutil/imgutils.h>
#include <libavcodec/avcodec.h>
#include <libavutil/hwcontext.h>
}

//"rtmp://10.20.47.83/live/test"
//"/home/yang/Desktop/11.mp4"
//"rtsp://77.110.228.219/axis-media/media.amp"
//"/home/yang/Downloads/movie.mp4"
const std::string src_url = "/home/yang/Downloads/movie.mp4";
RTSP::RTSP(QObject *parent)
    : QThread(parent)
    , m_audioDecode(new FAudioDecode(this))
{
}

RTSP::~RTSP()
{
    this->requestInterruption();
    wait();
}

void RTSP::run()
{
    //设置参数
    AVDictionary *format_opts = nullptr;
    av_dict_set(&format_opts, "stimeout", std::to_string(10 * 1000000).c_str(), 0); //设置链接超时时间（us）
    av_dict_set(&format_opts, "rtsp_transport", "tcp", 0); //设置推流的方式，默认udp。
    //打开输入流。
    AVFormatContext *pAVFomatContext = nullptr;
    int result = avformat_open_input(&pAVFomatContext, src_url.c_str(), nullptr, &format_opts);
    if (result < 0) {
        qWarning() << QStringLiteral("打开视频失败");
        return;
    }

    //查找流信息
    if (avformat_find_stream_info(pAVFomatContext, nullptr) < 0) {
        qWarning() << QStringLiteral("获取流信息失败");
        return;
    }
    //输出流信息
    av_dump_format(pAVFomatContext, 0, src_url.c_str(), 0);
    //查找视频流信息
    int videoStreamIndex = -1;
    int audioStreamIndex = -1;
    for (uint i = 0; i < pAVFomatContext->nb_streams; i++) {
        if (pAVFomatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
            //video_stream->codecpar->format AV_PIX_FMT_YUVJ420P 视频格式
            videoStreamIndex = static_cast<int>(i);
            m_videoDecode->initAVStream(pAVFomatContext->streams[i]);
        } else if (pAVFomatContext->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
            audioStreamIndex = static_cast<int>(i);
            m_audioDecode->initAVStream(pAVFomatContext->streams[i]);
        }
    }
    if (videoStreamIndex == -1)
        qWarning() << QStringLiteral("获取视频流索引失败");

    //创建一个Packet
    AVPacket *pAVPacket = av_packet_alloc();
    qWarning() << QStringLiteral("流初始化成功");
    while (!isInterruptionRequested()) {
        //读取数据
        if (av_read_frame(pAVFomatContext, pAVPacket) < 0) {
            break;
        }

        //视频数据
        if (pAVPacket->stream_index == videoStreamIndex) {
            AVPacket *pCopyAVPacket = av_packet_alloc();
            if (av_packet_ref(pCopyAVPacket, pAVPacket) == 0)
                m_videoDecode->addAVPacket(pCopyAVPacket); //这里后期需要处理，否则会存在很多
        } else if (pAVPacket->stream_index == audioStreamIndex) {
            AVPacket *pCopyAVPacket = av_packet_alloc();
            if (av_packet_ref(pCopyAVPacket, pAVPacket) == 0)
                m_audioDecode->addAVPacket(pCopyAVPacket); //这里后期需要处理，否则会存在很多
        }
        av_packet_unref(pAVPacket);
    }

    // 清理
    avformat_close_input(&pAVFomatContext);
    av_dict_free(&format_opts);
}
